from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.request import CommonRequest
import json
from common import errors
from common.constant import secret

client_ak = secret.ak if secret else 'your ak'
client_secret = secret.secret if secret else 'your secret'
SignName = secret.SignName if secret else 'your SignName'
TemplateCode = secret.TemplateCode if secret else 'your TemplateCode'

client = AcsClient(client_ak, client_secret, 'cn-qingdao')

request = CommonRequest()
request.set_accept_format('json')
request.set_domain('dysmsapi.aliyuncs.com')
request.set_method('POST')
request.set_protocol_type('https')  # https | http
request.set_version('2017-05-25')
request.set_action_name('SendSms')

request.add_query_param('SignName', SignName)
request.add_query_param('TemplateCode', TemplateCode)


def send_captcha_by_sms(phone_number, captcha):
    request.add_query_param('PhoneNumbers', phone_number)

    template_param = {
        'code': captcha
    }

    request.add_query_param('TemplateParam', json.dumps(template_param))
    response = client.do_action_with_exception(request)
    convert_response = str(response, encoding='utf-8')
    print("response", convert_response)
    if json.loads(convert_response)['Code'] != 'OK':
        raise errors.SendSmsFailedException(convert_response)
    return convert_response
